package com.xiangxiangjd.config.springsecurity;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Spring security登录失败处理类
 * * GYB
 * * 20190220
 */
@Component
public class MyAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {

        System.out.println("AuthenticationEntryPoint检测到异常:" + e);


        String msg = "账户名或者密码输入错误";

        if (e instanceof InternalAuthenticationServiceException) {
            msg = "用户名不存在";
        } else if (e instanceof BadCredentialsException) {
            msg = "密码错误";
        }


        System.out.println(msg);
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("UTF-8");

        JSONObject map = new JSONObject();
        map.put("code", "401");
        map.put("message", msg);

        httpServletResponse.getWriter().write(map.toString());


        httpServletResponse.getWriter().flush();
    }
}
